<?php

/**
 * 安装程序
 * 
 * @author ShuangYa
 * @package EUser
 * @category Install
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2015-2016 ShuangYa
 * @license http://lab.sylingd.com/go.php?name=euser&type=license
 */

use \sy\lib\db\YMongoDB;
use \sy\lib\YSecurity;
use \euser\libs\Common;

class Install {
	public static $securityKey;
	public static function Start() {
		self::checkEnv();
		$inputs = self::inputs();
		self::writeConfig($inputs);
		self::insertData($inputs);
		self::finish();
	}
	public static function AutoStart() {
		self::checkEnv();
		$inputs = self::autoInputs();
		self::writeConfig($inputs);
		self::insertData($inputs);
		self::finish();
	}
	//环境检查
	public static function checkEnv() {
		echo 'Checking environment ...', "\n";
		//PHP版本
		echo 'PHP Version: ';
		if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
			echo 'ok', "\n";
		} else {
			echo 'must be 5.4 or higher';
			exit;
		}
		//MongoDB扩展
		echo 'MongoDB extension: ';
		if (defined('MONGODB_VERSION') && version_compare(MONGODB_VERSION, '1.1.0', '>=')) {
			echo 'ok', "\n";
		} else {
			echo 'must be 1.1 or higher';
			exit;
		}
		//curl
		echo 'cURL extension: ';
		if (extension_loaded('curl')) {
			echo 'ok', "\n";
		} else {
			echo 'must be installed';
			exit;
		}
		echo 'Completed!', "\n\n";
	}
	//输入基本信息：从参数获取，用于自动安装
	public static function autoInputs() {
		$mongodb = [];
		//mongodb
		$inputs = getopt('', [
			'mongohost:',
			'mongoport:',
			'mongoname:',
			'mongoprefix:',
			'mongouser:',
			'mongopwd:',
			'securitykey:',
			'adminuser:',
			'adminpwd:'
		]);
		$mongodb['host'] = isset($inputs['mongohost']) ? $inputs['mongohost'] : '127.0.0.1';
		$mongodb['port'] = isset($inputs['mongoport']) ? $inputs['mongoport'] : '27017';
		$mongodb['name'] = isset($inputs['mongoname']) ? $inputs['mongoname'] : 'euser';
		$mongodb['prefix'] = isset($inputs['mongoprefix']) ? $inputs['mongoprefix'] : '';
		if (isset($inputs['mongouser'])) {
			$mongodbUser['user'] = $inputs['mongouser'];
			$mongodbUser['password'] = $inputs['mongopwd'];
		}
		$adminUser = isset($inputs['adminuser']) ? $inputs['adminuser'] : 'admin';
		$adminPassword = isset($inputs['adminpwd']) ? $inputs['adminpwd'] : 'admin';
		if (!isset($inputs['securitykey'])) {
			//生成新的密钥
			self::$securityKey = Common::getRandStr(8);
		} else {
			self::$securityKey = $inputs['securitykey'];
		}
		//完成
		echo "\n";
		return [$mongodb, $mongodbUser, [$adminUser, $adminPassword]];
	}
	//输入基本信息
	public static function inputs() {
		$mongodb = [];
		//mongodb地址
		echo 'Please input your MongoDB address(default is 127.0.0.1):';
		$mongodb['host'] = trim(fgets(STDIN));
		empty($mongodb['host']) && $mongodb['host'] = '127.0.0.1';
		//mongodb端口
		echo 'Please input your MongoDB port(default is 27017):';
		$mongodb['port'] = trim(fgets(STDIN));
		empty($mongodb['port']) && $mongodb['port'] = '27017';
		//mongodb认证
		echo 'Please input your MongoDB user(if have):';
		$user = trim(fgets(STDIN));
		if (!empty($user)) {
			$mongodbUser['user'] = $user;
			echo 'Please input your MongoDB password:';
			$mongodbUser['password'] = trim(fgets(STDIN));
		} else {
			$mongodbUser = NULL;
		}
		//数据库名称
		echo 'Please input your MongoDB database name(default is euser):';
		$mongodb['name'] = trim(fgets(STDIN));
		empty($mongodb['name']) && $mongodb['name'] = 'euser';
		//数据表前缀
		echo 'Please input your MongoDB table prefix(default is *null):';
		$mongodb['prefix'] = trim(fgets(STDIN));
		//管理员
		echo 'Please input the Admin account name(default is admin):';
		$adminUser = trim(fgets(STDIN));
		empty($adminUser) && $adminUser = 'admin';
		do {
			echo 'Please input the Admin account password(8-18):';
			$adminPassword = trim(fgets(STDIN));
		} while (strlen($adminPassword) < 8 || strlen($adminPassword) > 18);
		//密钥相关
		do {
			echo 'Do you want to generate a new securityKey?(y/n)';
			$isNewKey = strtolower(trim(fgets(STDIN)));
		} while ($isNewKey !== 'y' && $isNewKey !== 'n');
		if ($isNewKey === 'y') {
			//生成新的密钥
			self::$securityKey = Common::getRandStr(8);
		} else {
			echo 'Please input a securityKey:';
			self::$securityKey = trim(fgets(STDIN));
		}
		//完成
		echo "\n";
		return [$mongodb, $mongodbUser, [$adminUser, $adminPassword]];
	}
	//写入相关文件
	public static function writeConfig($inputs) {
		echo 'Writing to config file(s)', "\n";
		//基础配置
		$config = file_get_contents(Sy::$appDir . 'config.sample.php');
		echo 'euser/config.php ... ';
		//mongodb
		$config = str_replace('@mongodbHost', $inputs[0]['host'], $config);
		$config = str_replace('@mongodbPort', $inputs[0]['port'], $config);
		$config = str_replace('@mongodbName', $inputs[0]['name'], $config);
		$config = str_replace('@mongodbPrefix', $inputs[0]['prefix'], $config);
		if ($inputs[1] !== NULL) {
			$config = str_replace(' //@mongodbUser', ",\n\t\t'user' => '{$inputs[1]['user']}',\n\t\t'password' => '{$inputs[1]['password']}'", $config);
		} else {
			$config = str_replace(' //@mongodbUser', '', $config);
		}
		//密钥
		$config = str_replace('@securityKey', self::$securityKey, $config);
		$config = str_replace('@cookieKey', Common::getRandStr(8), $config);
		//写入
		if (file_put_contents(Sy::$appDir . 'config.php', $config) === FALSE) {
			echo 'fail!';
			exit;
		} else {
			echo 'success.', "\n";
		}
		//OAuth
		echo 'euser/data/oauth.serialize ... ';
		$oauth = [
			'enable' => ['baidu'],
			'baidu' => [
				'name' => '百度',
				'id' => '',
				'secret' => ''
			]
		];
		//写入
		if (file_put_contents(Sy::$appDir . 'data/oauth.serialize', serialize($oauth)) === FALSE) {
			echo 'fail!';
			exit;
		} else {
			echo 'success.', "\n";
		}
		echo 'Completed!', "\n\n";
	}
	//插入初始化数据
	public static function insertData($inputs) {
		echo 'Insert Data ...', "\n";
		//覆盖配置
		$mongo = $inputs[0];
		if (is_array($inputs[1])) {
			$mongo = array_merge($mongo, $inputs[1]);
		}
		Sy::$app['mongo'] = $mongo;
		Sy::$app['securityKey'] = self::$securityKey;
		$user = $inputs[2];
		//初始化OAuth
		$oauth = [
			'_id' => YMongoDB::MongoID('563cbb80474bdd821ef3ce1f'),
			'name' => 'OAuth',
			'secret' => md5(Common::getRandStr(16)),
			'type' => 'web'
		];
		YMongoDB::i()->select('app')->insert($oauth);
		//初始化管理员
		$admin = [
			'username' => $user[0],
			'password' => YSecurity::password(md5($user['password'])),
			'type' => 1
		];
		YMongoDB::i()->select('admin')->insert($oauth);
		echo 'Completed!', "\n\n";
	}
	public static function finish() {
		echo 'Finished.';
	}
	public static function GenData() {
		//测试环境一键安装
		$oauth = [
			'enable' => ['baidu'],
			'baidu' => [
				'name' => '百度',
				'id' => '',
				'secret' => ''
			]
		];
		//写入
		if (file_put_contents(Sy::$appDir . 'data/oauth.serialize', serialize($oauth)) === FALSE) {
			echo 'fail!';
			exit;
		} else {
			echo 'success.', "\n";
		}
		//初始化OAuth
		$oauth = [
			'_id' => YMongoDB::MongoID('563cbb80474bdd821ef3ce1f'),
			'name' => 'OAuth',
			'secret' => md5(Common::getRandStr(16)),
			'type' => 'web'
		];
		YMongoDB::i()->select('app')->insert($oauth);
		//初始化管理员
		$admin = [
			'username' => 'admin',
			'password' => YSecurity::password(md5('admin')),
			'type' => 1
		];
		YMongoDB::i()->select('admin')->insert($oauth);
		//初始化一般用户
		$_SERVER['REQUEST_TIME'] = time();
		Sy::model('user')->add([
			'name' => 'demo',
			'password' => 'demo',
			'mail' => 'example@example.com'
		]);
	}
}